'use strict';

webappApp.controller('NavCtrl', function($scope, spotService, $compile) {
  $scope.options = {
    minimumInputLength: 3,
    closeOnSelect: true,
    placeholder: "Find a Spot...",
    query: function (options) {
      var ctx = options.context;
        $scope.results = spotService.results.spots;
        spotService.query({
          q: options.term,
          cursor: ctx ? ctx.cursor : undefined
        },
        function(envelope) {
          if (options.context) {
            options.context.cursor = envelope.cursor;
          } else {
            options.context = {
              cursor: envelope.cursor
            };
          }
          options.callback({
            results: envelope.results || [],
            context: options.context,
            more: envelope.cursor
          });
          angular.forEach(envelope.results, function (r) {
            $scope.results[r.id] = r;
          });
        },
        function (reason) {
          options.callback({
            results: [],
            context: options.context,
            more: false
          });
        });
    },
    formatResult: function (object, container, query) {
      var html = angular.element('<search-result result="results[' + object.id + ']"/>'),
        linkFn = $compile(html);
        linkFn($scope);
      return html;
    },
    formatSelection: function (object, container,query) {
      return object.name;
    },
    formatNoMatches: function (term) {
      return 'No spots match <strong>' + term + '</strong>';
    }
  };
});
